package HomeWork8;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Work5 {
	    private static final String STUDENT = "name10.txt";
	    private static final String CALLED_STUDENTS = "called_students.txt";

	    public static void main(String[] args) {
	        try {
	            List<String> students = readStudentsFromFile(STUDENT);
	            List<Integer> calledStudentIndices = readCalledStudentIndices(CALLED_STUDENTS);

	            if (students.size() == calledStudentIndices.size()) {
	                // If all students have been called, clear the list to start a new round
	                calledStudentIndices.clear();
	            }

	            List<Integer> Indices = new ArrayList<>();
	            for (int i = 0; i < students.size(); i++) {
	                if (!calledStudentIndices.contains(i)) {
	                    Indices.add(i);
	                }
	            }

	            if (!Indices.isEmpty()) {
	                Collections.shuffle(Indices);
	                int calledIndex = Indices.get(0);
	                calledStudentIndices.add(calledIndex);
	                writeCalledStudentIndices(CALLED_STUDENTS, calledStudentIndices);

	                System.out.println(students.get(calledIndex));
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }

	    private static List<String> readStudentsFromFile(String file) throws IOException {
	        List<String> students = new ArrayList<>();
	        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
	            String line;
	            while ((line = reader.readLine()) != null) {
	                students.add(line);
	            }
	        }
	        return students;
	    }

	    private static List<Integer> readCalledStudentIndices(String filePath) throws IOException {
	        List<Integer> StudentIndices = new ArrayList<>();
	        File file = new File(filePath);
	        if (file.exists()) {
	            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
	                String line;
	                while ((line = reader.readLine()) != null) {
	                    StudentIndices.add(Integer.parseInt(line));
	                }
	            }
	        }
	        return StudentIndices;
	    }

	    private static void writeCalledStudentIndices(String filePath, List<Integer> calledStudentIndices) throws IOException {
	        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
	            for (Integer index : calledStudentIndices) {
	                writer.write(index.toString());
	                writer.newLine();
	            }
	        }
	    }
	}



